const db = wx.cloud.database()
Page({
  data: {
    user_url: 'cloud://peiyoukaoliantong-8e910u9ad85580.7065-peiyoukaoliantong-8e910u9ad85580-1317756011/静态资源/null_head.png',
    user_title: '',
    files: [],
    question: '',
    time: '',
    cloudfiles: [],
    user_default: '',
    title: '',
    vip: false
  },
  onLoad() {

    // 获取openid
    let openId = wx.getStorageSync('openId')
    // console.log(openId)
    // 查询数据库中是否有用户数据
    let res = db.collection("user").doc(openId).get()
      .then(res => {
        if (res.data.user_vip[0] != '') {
          var vip = true
        }
        this.setData({
          user_url: res.data.user_url,
          user_title: res.data.user_title,
          user_default: res.data.user_default,
          vip: vip
        })
      })
    this.setData({
      selectFile: this.selectFile.bind(this),
      uplaodFile: this.uplaodFile.bind(this)
    })

  },
  selectFile(files) {
    console.log('files', files)
    // 返回false可以阻止某次文件上传
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },

  uplaodFile(files) {
    console.log('files', files)
    return new Promise((resolve, reject) => {
      resolve({
        "urls": files.tempFilePaths
      })
    })
  },
  uploadError(e) {
    console.log('upload error', e.detail)
  },
  uploadSuccess(e) {
    console.log('upload success', e.detail.urls)
    this.setData({
      filePath: e.detail.urls
    })
  },







  async post() {
    let user_title = this.data.user_title
    let user_url = this.data.user_url
    let question = this.data.question
    let subject = this.data.user_default
    let title = this.data.title
    let vip = this.data.vip
    if (title != '' && question != '') {
      wx.showLoading({
        title: '上传中...',
      })
      let files = this.data.filePath
      console.log('文件本地地址', files)
      var newDateTime = Date.parse(new Date())
      var time = this.formatDate(newDateTime) //转换时间戳
      if (files!= undefined) {
        for (var i = 0; i < files.length; i++) {
          let filepath = files[i]
          await wx.cloud.uploadFile({
              cloudPath: 'question_img/' + newDateTime + '-' + i + '.png', // 上传至云端的路径
              filePath: filepath // 小程序临时文件路径，需结合小程序相关 API 获取
            })
            .then((res) => {
              this.setData({
                time: time
              })
              this.data.cloudfiles = this.data.cloudfiles.concat(res.fileID);


            });
        }
      }

      //****************** 连接数据库上传全部信息*******************************************/

      let cloudfiles = this.data.cloudfiles

      db.collection('square').add({
          data: {
            subject: subject,
            title: title,
            question: question,
            user_title: user_title,
            user_url: user_url,
            files: cloudfiles,
            time: time,
            times: newDateTime,
            vip: vip,
            like: 0,
            message: []

          },
        }).then(res => {
          wx.hideLoading()
          wx.showToast({
            title: '发表成功!',
            icon: "success",
            duration: 2000,
            mask: true
          })

          this.setData({
            camar: false,
            files: [],
            cloudfiles: []
          })
        
          wx.switchTab({
            url: '/pages/tabbar/square/square'
          });
      
        })
        .catch(res => {
          wx.showToast({
            title: '发表失败!',
            icon: "error",
            duration: 2000,
            mask: true
          })

        })
    }else{
      wx.showToast({
        title: '文本不能为空',
        icon: "error",
        duration: 2000,
        mask: true
      })
    }
  },
  getInputValue: function () {
    let content = this.data.content
  },



  // 时间戳转换函数
  formatDate: function (inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute;
  },
});